package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.Duration;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Autowired
    private ISeckillVoucherService seckillVoucherService;

    @Autowired
    private RedisIdWorker redisIdWorker;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private RedissonClient redissonClient;

    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;//在静态代码块里做初始化
    //创建一个线程池
    private static final ExecutorService SECKILL_ORDER_EXECUTOR = Executors.newSingleThreadExecutor();

    /*静态代码块加载lua脚本文件*/
    static {
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }

    @PostConstruct//是项目一启动，就加载秒杀的线程任务
    private void init() {
        //让这个类初始化完之后，执行线程任务
        SECKILL_ORDER_EXECUTOR.submit(new VoucherOrderHandler());
    }

    //声明一个匿名内部类供启动线程
    private class VoucherOrderHandler implements Runnable {
        @Override
        public void run() {
            while (true) {
                try {
                    //获取消息队列中的订单信息 XREADGOUP GOUP g1 c1 COUNT 1 BLOCK 2000 STREAM stream.orders >
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
                            StreamOffset.create("stream.orders", ReadOffset.lastConsumed())
                    );
                    //判断消息队列是否为空
                    if (list == null || list.isEmpty()) {
                        //开始下一次循环
                        continue;
                    }
                    //解析消息
                    MapRecord<String, Object, Object> record = list.get(0);
                    Map<Object, Object> recordValue = record.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(recordValue, new VoucherOrder(), true);
                    //创建订单
                    createVoucherOrder(voucherOrder);
                    //确认消息XACK  XACK g1 c1 消息id
                    stringRedisTemplate.opsForStream().acknowledge("stream.orders", "g1", record.getId());
                } catch (Exception e) {
                    log.error("处理订单异常", e);
                    handlePendingList();
                }
            }
        }

        private void handlePendingList() {
            while (true) {
                try {
                    //获取pendingList中的订单信息 XREADGOUP GOUP g1 c1 COUNT 1 STREAM stream.orders 0
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1),
                            StreamOffset.create("stream.orders", ReadOffset.from("0"))//获取pendingList中的第一条因处理异常而未被确认的消息
                    );
                    //判断pendingList是否为空
                    if (list == null || list.isEmpty()) {
                        //没有异常消息，结束
                        break;
                    }
                    //解析消息
                    MapRecord<String, Object, Object> record = list.get(0);
                    Map<Object, Object> recordValue = record.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(recordValue, new VoucherOrder(), true);
                    //创建订单
                    createVoucherOrder(voucherOrder);
                    //确认消息XACK
                    stringRedisTemplate.opsForStream().acknowledge("stream.orders", "g1", record.getId());
                } catch (Exception e) {
                    log.error("处理pendingList异常", e);
                    //休息下
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException ex) {
                        ex.printStackTrace();
                    }
                }
            }
        }
    }


    /*创建订单的方法*/
    private void createVoucherOrder(VoucherOrder voucherOrder) {
        /* 一人只能下一单*/
        Long voucherId = voucherOrder.getVoucherId();
        Long userId = voucherOrder.getUserId();
        //加个分布式锁
        //SimpleRedisLock redisLock = new SimpleRedisLock(stringRedisTemplate, "lock" + userId);
        //使用redisson里的锁
        RLock redisLock = redissonClient.getLock("lock:order" + userId);
        boolean isLock = redisLock.tryLock();//默认不等待，30秒钟释放锁
        //如果获取锁失败，返回错误信息
        if (!isLock) {
            log.error("不可以重复下单哟");
        }
        try {
            int count = query().eq("user_id", userId).eq("voucher_id", voucherId).count();
            if (count > 0) {
                log.error("哒咩，你已经下过单啦");//兜底检查
            }
            //足够，减去库存
            boolean success = seckillVoucherService.update().setSql("stock=stock-1")
                    .eq("voucher_id", voucherId)
                    .gt("stock", 0)//防止超卖的现象
                    .update();
            if (!success) {
                log.error("抢光啦");
            }
            //保存
            save(voucherOrder);
        } finally {
            redisLock.unlock();//释放锁
        }
    }


    /*从service来的方法，执行这里*/
    @Override
    public Result seckillVoucher(Long voucherId) {
        //获取用户id
        Long userId = UserHolder.getUser().getId();
        //获取订单id
        long orderId = redisIdWorker.nextId("order");
        //执行lua脚本
        Long result = stringRedisTemplate.execute(SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(),
                userId.toString(),
                String.valueOf(orderId)
        );
        assert result != null;
        int r = result.intValue();
        //判断是否具有购买条件
        //不具备
        if (r != 0) {
            return Result.fail(r == 1 ? "库存不足" : "不要重复下单");
        }
        return Result.ok(orderId);
    }

    @Transactional
    public Result creatVoucherOrder(Long voucherId) {
        /* 一人只能下一单*/
        Long userId = UserHolder.getUser().getId();
        //加个分布式锁
        //SimpleRedisLock redisLock = new SimpleRedisLock(stringRedisTemplate, "lock" + userId);
        //使用redisson里的锁
        RLock redisLock = redissonClient.getLock("lock:order" + userId);
        boolean isLock = redisLock.tryLock();//默认不等待，30秒钟释放锁
        //如果获取锁失败，返回错误信息
        if (!isLock) {
            return Result.fail("不可以重复下单哟");
        }
        try {
            int count = query().eq("user_id", userId).eq("voucher_id", voucherId).count();
            if (count > 0) {
                return Result.fail("哒咩，你已经下过单啦");
            }
            //足够，减去库存
            boolean success = seckillVoucherService.update().setSql("stock=stock-1")
                    .eq("voucher_id", voucherId)
                    .gt("stock", 0)//防止超卖的现象
                    .update();
            if (!success) {
                return Result.fail("抢光啦");
            }
            //创建订单
            VoucherOrder voucherOrder = new VoucherOrder();
            //券id
            voucherOrder.setVoucherId(voucherId);
            //用户id
            voucherOrder.setUserId(userId);
            //设置订单id
            long orderId = redisIdWorker.nextId("order");
            voucherOrder.setId(orderId);
            //保存
            save(voucherOrder);
            return Result.ok(orderId);
        } finally {
            redisLock.unlock();//释放锁
        }

    }
}
